# -*- coding: utf-8 -*-

import sys
import os
import requests
import json
import time
import re
import traceback,threading
import MySQLdb
import datetime

print('>>>正在初始化...')

DataBase = "sccplat"
HTTP_SB_URL = 'http://ydhzcms.bimsheng.com/daping/rest/people/'
proDir = os.path.split(os.path.realpath(__file__))[0]
SQL_CONNEC_URL = 'rm-bp1z598ttm5ahi9o15o.mysql.rds.aliyuncs.com'
SQL_USER_NAME = 'wangjun'
SQL_PWD = 'wj123456'
SQL_PORT = 3306
print('proDir---',proDir)
proDir = proDir.replace('\dist','')
import time
from selenium import webdriver
need_borwer_info_list = []
def loginurl(account='',password='',miniters=300,browser=None):
    cookie = None
    

    try:
        global need_borwer_info_list
        need_borwer_info_list = []#清空
        browser.get('https://pm.scg.cn/SCG/SSO/Login')
        time.sleep(2)
        #定位到账号的输入框
        id_input = browser.find_element_by_xpath('//input[@id="j_username"]')
        time.sleep(2)
        id_input.send_keys(account)
        #定位到密码输入框，输入密码
        pw_input = browser.find_element_by_xpath('//input[@id="j_password"]')
        pw_input.send_keys(password)
        time.sleep(1)
        #点击登录按钮
        browser.find_element_by_xpath('//button[@class="white loginBt"]').click()
        time.sleep(2)
        # #获取登录的cookie
        cookie = browser.get_cookies()
        
        cookiearr = []
        for item in cookie:
            cookiearr.append(item['name']+'='+item['value'])
        cookiestr = ';'.join(cookiearr)
        print('cookiestr---',cookiestr)

        # cookiestr = 'ASP.NET_SessionId=nbukoq5qbzwe0obatd3cdndm;ext-EditUserName=s%3Add651'
        # GetTodayPcNum('427191101002353',cookiestr)#更新公司的项目
        
        ###主执行程序开始
        projects = selectFDb('sjsso_projects')#获取项目列表，一个个爬取更新
   
        GetCompanyYgCheckOut(projects,cookiestr)#h获取所有项目的进出记录


        if len(need_borwer_info_list)>0:
            for iten in need_borwer_info_list:
                time.sleep(2)
                GetInfoBybrower(browser,iten['phid'],iten['PhidWorktype'],iten['PhidTeamsgrId'],iten['PhidCrafttype'],iten['PhidCraftComp'])    
    
    except:
        traceback.print_exc()
        print('异常处理')
    
    
    # return cookie

def GetInfoBybrower(browser,phid,PhidWorktype_code,PhidTeamsgrId_code,PhidCrafttype_code,PhidCraftComp_code,**kwargs):
    try:
        print('PhidCraftComp_code----',PhidCraftComp_code)
        
        browser.get('https://pm.scg.cn/i8/PMS/PMS/YgCraftInfo/YgCraftInfoEdit?id='+str(phid)+'&otype=view&AppTitle=%E5%8A%B3%E5%8A%A1%E5%B7%A5%E4%BF%A1%E6%81%AF')
        time.sleep(2)
        PhidWorktype = browser.find_element_by_name('PhidWorktype')
        # print('工种类型---',PhidWorktype.get_attribute('value'))

        PhidTeamsgrId = browser.find_element_by_name('PhidTeamsgrId')
        # print('班组信息---',PhidTeamsgrId.get_attribute('value'))

        PhidCrafttype = browser.find_element_by_name('PhidCrafttype')
        # print('工种信息---',PhidCrafttype.get_attribute('value'))

        PhidCraftComp = browser.find_element_by_name('PhidCraftComp')
        print('劳务---',PhidCraftComp.get_attribute('value'))
        time.sleep(1)
        worktypeandteamdataexecute(PhidCrafttype.get_attribute('value'),PhidWorktype.get_attribute('value'),PhidTeamsgrId.get_attribute('value'),PhidCraftComp.get_attribute('value'),PhidCrafttype_code,PhidWorktype_code,PhidTeamsgrId_code,PhidCraftComp_code)
        time.sleep(1)
    except Exception as e:
        traceback.print_exc()
        print("获取浏览器端用户信息错误")
#获取用户信息https://pm.scg.cn/i8/PMS/PMS/YgCraftInfo/GetYgCraftInfo
def GetYgCraftInfo(phid,tabtype,cookiestr,project_code):
    try:
        global need_borwer_info_list
        data = {}
        tbconfig = {
            0: "has_ruku",
            1: "content", 
            2: "PhId",
            3: "PhidPc",
            4: "Sex",

            5: "Tel",
            6: "Birthday",
            7: "yg_Id",
            8: "Address",
            9: "PhidTeamsgrId",
            10: "PhidWorktype",
            11: "PhidCrafttype",
            12: "PhidCraftComp",
            13: "CraftNo",
            14: "CraftName",
            15: "Cardno",

            16: "EnterDt",
            17: "ExitDt",
            18: "Age",
            19: "PhidOcode",
            20: "NowAddress",
            21: "RecentPic",
            22: "CertPic",
            23: "CertType",
            24: "GrantOrg",
            25: "HkPersonCardno",
            26: "NgInsertDt",
            27: "NgUpdateDt",
            28: "Creator",
            29: "Editor",
            30: "CurOrgId",
            31: "project_code"


        }
        header = {
            "Cookie":cookiestr
        }
        pic_url = "https://pm.scg.cn/i8/NG3Resource/pic/gc/CraftInfo/"
        jiekou_url = 'https://pm.scg.cn/i8/PMS/PMS/YgCraftInfo/GetYgCraftInfo?id='+str(phid)+'&tabtype='+tabtype
        result = json.loads(requests.get(jiekou_url,headers=header).text)
        


        item_list = []
        obj = {}
        obj = result['Data']
        obj['has_ruku'] = 1
        obj['yg_Id'] = obj['Id']
        obj['project_code'] = project_code
        obj['content'] = ''
        if obj['Sex'] == '1':
            obj['Sex'] = '女'
        else:
            obj['Sex'] = '男'

        if obj['RecentPic']:
            obj['RecentPic'] = pic_url+obj['RecentPic']

        if obj['CertPic']:
            obj['CertPic'] = pic_url+obj['CertPic']
        item_list.append(obj)
        

        if(len(item_list)>0):
            save2Db(item_list,'sjsso_worker',list(tbconfig.values()))

        
        # GetInfoBybrower(phid,obj['PhidWorktype'],obj['PhidTeamsgrId'],obj['PhidCrafttype'])
    except Exception as e:
        traceback.print_exc()
        print('获取信息失败')
#获取所有项目的出入记录
def GetCompanyYgCheckOut(projects,cookiestr):
    curr_time = datetime.datetime.now()
    curr_time = curr_time.strftime('%Y-%m-%d')
    for pcid in projects:
        try:
            data = {}
            tbconfig = {
                0: "PhId",
                1: "Name", 
                2: "Sex",
                3: "Crafttype",
                4: "PhidWorktype",
                5: "PhidCompane1",
                6: "CompaneName1",
                7: "CompaneSimpName1",
                8: "PhidCompane2",
                9: "CompaneName2",
                10: "CompaneSimpName2",
                11: "InDormDt",
                12: "OutDormDt",
                13: "InBuildDt",
                14: "OutBuildDt",
                15: "CheckNowDt",
                16: "OrgName",
                17: "Dormitory",
                18: "today",
                19: "project_code"
            }
            header = {
                "Cookie":cookiestr
            }
            jiekou_url = 'https://pm.scg.cn/i8/PMS/DCS/DcsCommandPortal/GetCompanyYgCheckOut?pcid='+pcid+'&limit=10'
            result = json.loads(requests.get(jiekou_url,headers=header).text)


            

            item_list = []
            for item in result['items']:
                # print('name--',item['name'],'--code--',item['code'],'--value--',item['value'],'--value1--',item['value1'])
                obj = {}
                obj['PhId'] = item['PhId']
                obj['Name'] = item['Name']
                obj['project_code'] = pcid
                obj['Sex'] = item['Sex']
                obj['Crafttype'] = item['Crafttype']
                obj['PhidWorktype'] = item['PhidWorktype']
                obj['PhidCompane1'] = item['PhidCompane1']
                obj['CompaneName1'] = item['CompaneName1']
                obj['CompaneSimpName1'] = item['CompaneSimpName1']
                obj['CompaneSimpName2'] = item['CompaneSimpName2']
                obj['PhidCompane2'] = item['PhidCompane2']
                obj['CompaneName2'] = item['CompaneName2']
                obj['CheckNowDt'] = item['CheckNowDt']
                # if obj['CheckNowDt']:
                #     curr_time = obj['CheckNowDt'][0:10]

                obj['InDormDt'] = None
                if item['InDormDt']:
                    obj['InDormDt'] = curr_time +' '+ item['InDormDt']

                obj['OutDormDt'] = None
                if item['OutDormDt']:
                    obj['OutDormDt'] = curr_time +' '+ item['OutDormDt']
                
                obj['InBuildDt'] = None
                if item['InBuildDt']:
                    obj['InBuildDt'] = curr_time +' '+ item['InBuildDt']

                obj['OutBuildDt'] = None
                if item['OutBuildDt']:
                    obj['OutBuildDt'] = curr_time +' '+ item['OutBuildDt']
                
                
                obj['OrgName'] = item['OrgName']
                obj['Dormitory'] = item['Dormitory']
                obj['today'] = curr_time
                
                item_list.append(obj)

            if(len(item_list)>0):
                save2Db(item_list,'sjsso_worker_records',list(tbconfig.values()),curr_time=curr_time,cookiestr=cookiestr,project_code=pcid)
            
            # break
        except Exception as e:
            traceback.print_exc()
            print('获取信息失败')

        # break
#根据公司id获取项目信息
def GetTodayPcNum(orid,cookiestr):
    try:
        data = {}
        tbconfig = {
            0: "company",
            1: "name", 
            2: "code",
            3: "value",
            4: "value1",
        }
        header = {
            # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0",
            # "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            # "Accept-Encoding":"gzip, deflate, br",
            # "Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
            # "Connection":"keep-alive",
            # "Host":"pm.scg.cn",
            # "Upgrade-Insecure-Requests":'1',
            "Cookie":cookiestr
        }
        jiekou_url = 'https://pm.scg.cn/i8/PMS/DCS/DcsOrganizePortal/GetTodayPcNum?orid='+orid
        result = json.loads(requests.get(jiekou_url,headers=header).text)
        print(type(result['items']))
        print(result['items'])

        item_list = []
        for item in result['items']:
            print('name--',item['name'],'--code--',item['code'],'--value--',item['value'],'--value1--',item['value1'])
            obj = {}
            obj['name'] = item['name']
            obj['code'] = item['code']
            obj['value'] = item['value']
            obj['value1'] = item['value1']
            obj['company'] = orid
            item_list.append(obj)

        if(len(item_list)>0):
            save2Db(item_list,'sjsso_projects',list(tbconfig.values()),orid=orid)


        
    except Exception as e:
        traceback.print_exc()
        print('获取信息失败')
class MainThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        # config = configparser.ConfigParser()
        
        # configPath = os.path.join(proDir, "config.ini")
        # config.read(configPath)
        # username = config.get('config','username')
        # password = config.get('config','password')
        # miniters = int(config.get('config','miniters'))

        ####linux下开始
        options = webdriver.FirefoxOptions()
        options.add_argument('--headless')
        #linux下结束

        ####window下开始
        #创建一个浏览器对象,windows
        # profile=webdriver.FirefoxProfile()
        # profile.accept_untrusted_certs=True
        # geckodriverPath = os.path.join(proDir, "geckodriver")
        # browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) 
        ####window下结束
        while True:
            try:
                # loginurl(username,password,miniters)
                browser = webdriver.Firefox(firefox_options=options)#linux
                # browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) #windows版
                pwd = selectFDb('sjsso_account',name='18616728227')
                print('pwd---',pwd)
                if pwd:
                    loginurl('18616728227',pwd,60,browser)
                if browser:
                    browser.close()
                    browser = None

                curr_time = datetime.datetime.now()
                print("线程在跑----",curr_time.strftime('%Y-%m-%d %H:%M:%S'))

            except Exception as e:
                print('登录主线程报错，继续执行。。。。')
                traceback.print_exc()
            
            time.sleep(300)

def updategongzanalyse():
    results = None
    while True:
        try:
            db = MySQLdb.connect(SQL_CONNEC_URL, SQL_USER_NAME, SQL_PWD, DataBase,charset='utf8', port=SQL_PORT)
            cursor = db.cursor()
            break
        except Exception as e:
            print('%s' % e)
            time.sleep(5)
    try:
        has_sql = '''SELECT PhidWorktype,PhidWorktype_name,PhidCrafttype,PhidCrafttype_name,project_code from sjsso_worker where PhidWorktype_name is not null and PhidCrafttype_name is not null and project_code is not null'''
        cursor.execute(has_sql)
        for item in cursor.fetchall():
            print('item---',item)
            crafytype2_analyse_sql = '''SELECT id from sjsso_crafttype_analyse where  code="{PhidCrafttype_code}" and project_code="{project_code}"'''.format(PhidCrafttype_code=item[2],project_code=item[4])
            crafytype2_analyse_count = cursor.execute(crafytype2_analyse_sql)
            if crafytype2_analyse_count==0:
                crafytype2_analyse_insert_sql = '''INSERT ignore INTO sjsso_crafttype_analyse(code,name,parent_code,parent_name,project_code) VALUES("{code}","{name}","{parent_code}","{parent_name}","{project_code}")'''.format(code=item[0],name=item[1],parent_code=item[2],parent_name=item[3],project_code=item[4])
                cursor.execute(crafytype2_analyse_insert_sql)
                db.commit()
    except Exception as e:
        traceback.print_exc()
    
    db.close()


    return results

def selectFDb(table,**kwargs):
    results = None
    while True:
        try:
            db = MySQLdb.connect(SQL_CONNEC_URL, SQL_USER_NAME, SQL_PWD, DataBase,charset='utf8', port=SQL_PORT)
            cursor = db.cursor()
            break
        except Exception as e:
            print('%s' % e)
            time.sleep(5)
    try:
        update_list = []
        if table=='sjsso_projects':
            has_sql = '''SELECT code from {table}'''.format(table=table)
            cursor.execute(has_sql)
            results = []
            for field in cursor.fetchall():
                results.append(field[0])
        elif table == 'sjsso_account':
            has_sql = '''SELECT pwd from {table} where account="{name}"'''.format(table=table,name=kwargs['name'])
            cursor.execute(has_sql)
            results = cursor.fetchone()[0]
    except Exception as e:
        traceback.print_exc()
    
    db.close()


    return results

def save2Db(itemList, table, colList,**kwargs):
    if len(itemList) == 0:
        return

    while True:
        try:
            db = MySQLdb.connect(SQL_CONNEC_URL, SQL_USER_NAME, SQL_PWD, DataBase,charset='utf8', port=SQL_PORT)
            cursor = db.cursor()
            break
        except Exception as e:
            print('%s' % e)
            time.sleep(5)

    sql = '''INSERT ignore INTO {table}('''.format(table=table)

    #做一层过滤，如果时间改变了，才需要更新，之前已经更新过了就无需再更新了
    update_list = []
    if table=='sjsso_worker':
        for item in itemList:
            has_sql = '''SELECT id from {table} where yg_Id="{yg_Id}" and PhId="{PhId}"'''.format(table=table,yg_Id=item['yg_Id'],PhId=item['PhId'])
            # print has_sql
            count = cursor.execute(has_sql)
            # print 'count---',count
            if count==0:
                update_list.append(item)

            #如果有了就不用去入库班组了
            team_sql = '''SELECT id from sjsso_teams where  code="{PhidTeamsgrId_code}"'''.format(PhidTeamsgrId_code=item['PhidTeamsgrId'])
            team_count = cursor.execute(team_sql)

            crafytype_sql = '''SELECT id from sjsso_crafttype where  code="{PhidWorktype_code}"'''.format(PhidWorktype_code=item['PhidWorktype'])
            crafytype_count = cursor.execute(crafytype_sql)

            crafytype2_sql = '''SELECT id from sjsso_crafttype where  code="{PhidCrafttype_code}"'''.format(PhidCrafttype_code=item['PhidCrafttype'])
            crafytype2_count = cursor.execute(crafytype2_sql)

            #劳务公司入库
            labour_sql = '''SELECT id from sjsso_labour_company where  code="{PhidCraftComp}"'''.format(PhidCraftComp=item['PhidCraftComp'])
            labour_count = cursor.execute(labour_sql)
            if team_count==0 or crafytype_count==0 or crafytype2_count==0 or labour_count==0:
                need_borwer_info_list.append({'phid':item['PhId'],'PhidWorktype':item['PhidWorktype'],'PhidTeamsgrId':item['PhidTeamsgrId'],'PhidCrafttype':item['PhidCrafttype'],'PhidCraftComp':item['PhidCraftComp']})
 

    elif table=='sjsso_projects':
        for item in itemList:
            has_sql = '''SELECT id from {table} where code="{code}" and company="{orid}"'''.format(table=table,code=item['code'],orid=kwargs['orid'])
            # print has_sql
            count = cursor.execute(has_sql)
            # print 'count---',count
            if count==0:
                update_list.append(item)
    elif table=='sjsso_worker_records':
        for item in itemList:
            has_sql = '''SELECT id from {table} where  Name="{Name}" and date_format(today,"%Y-%m-%d")="{today}"'''.format(table=table,Name=item['Name'],today=kwargs['curr_time'])
            
            count = cursor.execute(has_sql)
            if count==0:
                update_list.append(item)
            else:
                #更新时间
                has2_sql = '''SELECT id from {table} where CheckNowDt="{CheckNowDt}" and Name="{Name}" and date_format(today,"%Y-%m-%d")="{today}"'''.format(table=table, CheckNowDt=item['CheckNowDt'],Name=item['Name'],today=kwargs['curr_time'])
 
                if not cursor.execute(has2_sql)==0:
                    update2_sql = '''UPDATE {table} set CheckNowDt="{CheckNowDt}",InDormDt="{InDormDt}",OutBuildDt="{OutBuildDt}",InBuildDt="{InBuildDt}",OutDormDt="{OutDormDt}" where Name="{Name}" and PhId="{PhId}" and PhidCompane1="{PhidCompane1}" and date_format(today,"%Y-%m-%d")="{today}"'''.format(table=table,CheckNowDt=item['CheckNowDt'],InDormDt=item['InDormDt'],OutBuildDt=item['OutBuildDt'],InBuildDt=item['InBuildDt'],OutDormDt=item['OutDormDt'],Name=item['Name'],PhId=item['PhId'],PhidCompane1=item['PhidCompane1'],today=kwargs['curr_time'])
                    cursor.execute(update2_sql)
                    db.commit()

            #判断是否加入员工库
            has_ygrk_sql = '''SELECT id from {table} where PhId="{PhId}"'''.format(table='sjsso_worker',PhId=item['PhId'])
            # print has_sql
            ygcount = cursor.execute(has_ygrk_sql)
            # print 'count---',count
            if ygcount==0:
                GetYgCraftInfo(item['PhId'],'ygcraftinfo',kwargs['cookiestr'],kwargs['project_code'])#获取员工信息

            

    for col in colList:

        sql = sql + col + ","
    sql = sql[:-1] + ") VALUES"

    for each in update_list:
        sql = sql + "("
        for col in colList:
            sql = sql + "'" + str(each[col]) + "',"
        sql = sql[:-1] + "),"
    sql = sql[:-1]

    try:
        if len(update_list)>0:
            cursor.execute(sql)
            db.commit()
    except Exception as e:
        # traceback.print_exc()
        print('%s' % e)
        db.rollback()

    db.close()

#工种类型和班组的处理
def worktypeandteamdataexecute(PhidCrafttype,PhidWorktype,PhidTeamsgrId,PhidCraftComp,PhidCrafttype_code,PhidWorktype_code,PhidTeamsgrId_code,PhidCraftComp_code):
    while True:
        try:
            db = MySQLdb.connect(SQL_CONNEC_URL, SQL_USER_NAME, SQL_PWD, DataBase,charset='utf8', port=SQL_PORT)
            cursor = db.cursor()
            break
        except Exception as e:
            print('%s' % e)
            time.sleep(5)

    try:
        team_sql = '''SELECT id from sjsso_teams where  code="{PhidTeamsgrId_code}"'''.format(PhidTeamsgrId_code=PhidTeamsgrId_code)

        team_count = cursor.execute(team_sql)
        if team_count==0:
            team_insert_sql = '''INSERT ignore INTO sjsso_teams(code,name) VALUES("{code}","{name}")'''.format(code=PhidTeamsgrId_code,name=PhidTeamsgrId)
            
            cursor.execute(team_insert_sql)
            db.commit()

        #工种类型
        crafytype_sql = '''SELECT id from sjsso_crafttype where  code="{PhidWorktype_code}"'''.format(PhidWorktype_code=PhidWorktype_code)
        crafytype_count = cursor.execute(crafytype_sql)
        if crafytype_count==0:
            crafytype_insert_sql = '''INSERT ignore INTO sjsso_crafttype(code,name) VALUES("{code}","{name}")'''.format(code=PhidWorktype_code,name=PhidWorktype)
            cursor.execute(crafytype_insert_sql)
            db.commit()

        #工种执行
        crafytype2_sql = '''SELECT id from sjsso_crafttype where  code="{PhidCrafttype_code}"'''.format(PhidCrafttype_code=PhidCrafttype_code)
        crafytype2_count = cursor.execute(crafytype2_sql)
        if crafytype2_count==0:
            crafytype2_insert_sql = '''INSERT ignore INTO sjsso_crafttype(code,name,parent_code) VALUES("{code}","{name}","{parent_code}")'''.format(code=PhidCrafttype_code,name=PhidCrafttype,parent_code=PhidWorktype_code)
            cursor.execute(crafytype2_insert_sql)
            db.commit()

        #劳务执行
        labour_sql = '''SELECT id from sjsso_labour_company where  code="{PhidCraftComp_code}"'''.format(PhidCraftComp_code=PhidCraftComp_code)
        labour_count = cursor.execute(labour_sql)
        if labour_count==0:
            labour_insert_sql = '''INSERT ignore INTO sjsso_labour_company(code,name) VALUES("{code}","{name}")'''.format(code=PhidCraftComp_code,name=PhidCraftComp)
            cursor.execute(labour_insert_sql)
            db.commit()

        #工种分析执行
        # crafytype2_analyse_sql = '''SELECT id from sjsso_crafttype_analyse where  code="{PhidCrafttype_code}" and project_code="{project_code}"'''.format(PhidCrafttype_code=PhidCrafttype_code,project_code=project_code)
        # crafytype2_analyse_count = cursor.execute(crafytype2_analyse_sql)
        # if crafytype2_analyse_count==0:
        #     crafytype2_analyse_insert_sql = '''INSERT ignore INTO sjsso_crafttype_analyse(code,name,parent_code,parent_name,project_code) VALUES("{code}","{name}","{parent_code}","{parent_name}","{project_code}")'''.format(code=PhidCrafttype_code,name=PhidCrafttype,parent_code=PhidWorktype_code,parent_name=PhidWorktype,project_code=project_code)
        #     cursor.execute(crafytype2_analyse_insert_sql)
        #     db.commit()

    except Exception as e:
        traceback.print_exc()
    


    db.close()

#工种处理
def crafttypedataexecute():
    while True:
        try:
            db = MySQLdb.connect(SQL_CONNEC_URL, SQL_USER_NAME, SQL_PWD, DataBase,charset='utf8', port=SQL_PORT)
            cursor = db.cursor()
            break
        except Exception as e:
            print('%s' % e)
            time.sleep(5)

    #工种处理
    gongzhong_sql = '''SELECT distinct Crafttype from sjsso_worker_records'''

    cursor.execute(gongzhong_sql)
    for field in cursor.fetchall():
        has_sql = '''SELECT id from sjsso_crafttype where  name="{name}"'''.format(name=field[0])
        count = cursor.execute(has_sql)
        print(count)
        if count==0:
            user_record_sql = '''SELECT r.Name,r.Crafttype,w.PhidCrafttype from sjsso_worker_records as r  left join sjsso_worker as w on r.PhId=w.PhId where r.Crafttype="{Crafttype}"'''.format(Crafttype=field[0])
            cursor.execute(user_record_sql)
            resobj = cursor.fetchone()

            insert_sql = '''INSERT ignore INTO sjsso_crafttype(code,name) VALUES("{code}","{name}")'''.format(code=resobj[2],name=resobj[1])
            cursor.execute(insert_sql)
            db.commit()

    db.close()
import configparser
if __name__ == '__main__':
    print(">>>>>>>>  login")
    
    MainThread().start()
    print('执行成功')
    time.sleep(2)

    
    # try:
    #     updategongzanalyse()
    #     pwd = selectFDb('sjsso_account',name='dd651')
    #     print('pwd---',pwd)
    #     if pwd:
    #         browser = None
    #         profile=webdriver.FirefoxProfile()
    #         profile.accept_untrusted_certs=True
    #         geckodriverPath = os.path.join(proDir, "geckodriver")#将驱动放在同目录下
    #         browser=webdriver.Firefox(firefox_profile=profile,executable_path=geckodriverPath) #windows版
    #         # loginurl('dd651','Xrj888888',60,browser)
            
    #         loginurl('dd651',pwd,60,browser)
    # except Exception as e:
    #     print('登录主线程报错，继续执行。。。。')
    #     traceback.print_exc()

